﻿using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Services.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Repository;
using Razor.Templating.Core;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class WorkflowCommonController : ControllerBase
    {
        private readonly IConfiguration configuration;
        private readonly IWorkflowCommon workflowCommon;
        private readonly ILogger<WorkflowCommonController> logger;
        private readonly UserBaseInforDataContext userBaseInforDataContext;

        private readonly string encyptUserInfo = "/api/UserLoginInforDecrypt/Encypt";
        private readonly string MailSendUrl = "/api/MailSender/SendMailToQueue";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_workflowCommon"></param>
        /// <param name="_logger"></param>
        /// <param name="_configuration"></param>
        public WorkflowCommonController(IWorkflowCommon _workflowCommon,
            ILogger<WorkflowCommonController> _logger,
            IConfiguration _configuration,
            UserBaseInforDataContext _userBaseInforDataContext)
        {
            workflowCommon = _workflowCommon;
            configuration = _configuration;
            logger = _logger;
            userBaseInforDataContext = _userBaseInforDataContext;
        }

        /// <summary>
        /// 抄送
        /// </summary>
        /// <param name="cclist"></param>
        /// <returns></returns>
        [HttpPost("AddCCTask")]
        public async Task<IActionResult> AddCCList(List<ToReadDto> cclist)
        {
            var result = await workflowCommon.AddCCTask(cclist);
            return Ok(result);
        }

        /// <summary>
        /// 流程作废
        /// </summary>
        /// <param name="procInstId"></param>
        /// <returns></returns>
        [HttpPost("CancelWorkItem")]
        public async Task<IActionResult> CancelWorkItem(string procInstId)
        {
            var workflowHost = configuration.GetSection("WorkflowHost").Value;
            var url = $"{workflowHost}/api/WorkflowManagement/GotoActivity?procInstID={procInstId}&actName=End";
            var result = await HttpHelper.PostAsync<bool>(url, "");
            return Ok(result);
        }

        /// <summary>
        /// 节点跳转
        /// </summary>
        /// <param name="procInstId"></param>
        /// <param name="actName"></param>
        /// <returns></returns>
        [HttpGet("GotoActivity")]
        public async Task<IActionResult> GotoActivity(string procInstId,string actName)
        {
            var workflowHost = configuration.GetSection("WorkflowHost").Value;
            var url = $"{workflowHost}/api/WorkflowManagement/GotoActivity?procInstID={procInstId}&actName={actName}";
            var result = await HttpHelper.PostAsync<bool>(url, "");
            return Ok(result);
        }

        /// <summary>
        /// 流程委托
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="userId"></param>
        /// <param name="toUserId"></param>
        /// <returns></returns>
        [HttpPost("WorkItemRedirect")]
        public async Task<IActionResult> WorkItemRedirect(string sn, string userId, string toUserId)
        {
            var workflowHost = configuration.GetSection("WorkflowHost").Value;
            var url = $"{workflowHost}/api/WorkflowTaskRedirect";
            var jsonObj = new { SerialNumber = sn, OriginalUser = userId, RedirectToUser = toUserId };
            var result = await HttpHelper.PostAsync<bool>(url, JsonConvert.SerializeObject(jsonObj));
            return Ok(result);
        }

        /// <summary>
        /// 邮件审批 [转办]
        /// </summary>
        /// <param name="mail"></param>
        /// <returns></returns>
        [HttpPost("SendEmail")]
        public async Task<IActionResult> SendEmail(EmailService.MailModel mail)
        {
            var serviceSoapClient = new EmailService.VertivWorkflowSMOServiceSoapClient(EmailService.VertivWorkflowSMOServiceSoapClient.EndpointConfiguration.VertivWorkflowSMOServiceSoap);
            await serviceSoapClient.SendEmailAsync(mail);
            return Ok("200");
        }

        /// <summary>
        /// 流程重试
        /// </summary>
        /// <param name="procInstId"></param>
        /// <returns></returns>
        [HttpPost("Retry")]
        public async Task<IActionResult> Retry(int procInstId)
        {
            //获取errorID
            var errorID = await workflowCommon.GetErrorID(procInstId);

            var workflowHost = configuration.GetSection("WorkflowHost").Value;
            var url = $"{workflowHost}/api/WorkflowManagement/Retry?procInstID={procInstId}&errorID={errorID}";
            var result = await HttpHelper.PostAsync<bool>(url, "");
            return Ok(result);
        }

        /// <summary>
        /// 邮件知会
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost("SendEmailNotification")]
        public async Task<IActionResult> SendEmailNotification(InformInformation info)
        {
            try
            {
                if (info != null)
                {
                    List<EmailParameter> emaiList = new List<EmailParameter>();
                    info.UserIDList.ForEach((x) => {
                        emaiList.Add(new EmailParameter
                        {
                            ProcInstId = info.ProcInstId,
                            Subject = info.Subject,
                            FunctionId = info.FunctionId,
                            DocumentDistributionUserID = x,
                            ViteFormUrl = info.ViteFormUrl,
                        }); ;
                    });

                    //发送邮件
                    if (emaiList.Any())
                    {
                        var html = await RazorTemplateEngine.RenderAsync("~/Pages/EmailTemplates/VehicleMaintenance/InvalidEmailSendingIndex.cshtml");
                        var ValidationProblemTrackingFrontEndHost = configuration.GetSection("ValidationProblemTracking").Value;
                        html = html.Replace("[ViteFormUrl]", ValidationProblemTrackingFrontEndHost);
                        workflowCommon.EmailSending(emaiList, html);
                    }
                }
                logger.LogInformation($"邮件知会（中试验证问题处理电子流）,流程实例号：{info.ProcInstId},标题：{info.Subject},时间：{DateTime.Now}");
                return Ok(true);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"邮件知会（中试验证问题处理电子流）,流程实例号：{info.ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                return Ok(false);
            }
        }

    }
}
